package com.yc.baihe.servlets;

import com.yc.baihe.beans.BhUser;
import com.yc.baihe.beans.Story;
import com.yc.baihe.beans.UserList;
import com.yc.baihe.biz.IBhUserBiz;
import com.yc.baihe.biz.IUserListBiz;
import com.yc.baihe.biz.StoryBiz;
import com.yc.baihe.biz.impl.BhUserBizImpl;
import com.yc.baihe.biz.impl.StoryBizImpl;
import com.yc.baihe.biz.impl.UserListBizImpl;
import com.yc.baihe.times.MyTimer;
import com.yc.baihe.utils.AgeUtil;
import com.yc.baihe.utils.MailUtil;
import com.yc.baihe.utils.Reflect;
import com.yc.baihe.utils.SessionAttributeNames;

import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Random;
import javax.servlet.ServletException;
import javax.servlet.http.*;

import net.sf.json.JSONObject;

public class RegLogServlet extends CommonServlet{
	private static final long serialVersionUID = 1L;
	private IBhUserBiz bhUserBiz= new BhUserBizImpl();
	private IUserListBiz userListBiz=new UserListBizImpl();
	private StoryBiz storyBiz=new StoryBizImpl();
	private PrintWriter out;
	private HttpSession session;

	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
		super.doPost(request, response);
		String op = request.getParameter("op");
		out = response.getWriter();
		session = request.getSession();
		if ("checkEmail".equals(op)){
			checkEmail(request, response);
		}else if ("sendCode".equals(op)){
			sendCode(request, response);
		}else if("regUser".equals(op)){
			regUser(request, response);
		}else if ("userLogin".equals(op)){
			userLogin(request, response);
		}else if ("getUserLoginInfo".equals(op)){
			getUserLoginInfo(request, response);
		}else if ("userOutLogin".equals(op)){
			userOutLogin(request, response);
		}else if("getNow".equals(op)){
			getNow(request,response);
		}else if("doSearch".equals(op)){
			doSearch(request,response);
		}else if("changeList".equals(op)){
			changeList(request,response);
		}
	}


	/**
	 * 换一换
	 * @param request
	 * @param response
	 */
	private void changeList(HttpServletRequest request,HttpServletResponse response) {
		Object obj = session.getAttribute(SessionAttributeNames.CURRENTUSERSINFO);  
		BhUser uf = (BhUser)obj;
		int buid=uf.getBuid(); //用户序列号
		List<Map<String,Object>> loginUserlist=userListBiz.findbByBuid(buid);
		session.setAttribute(SessionAttributeNames.CURRENTUSERLIST,loginUserlist); //存储当前用户详细信息
		String sex=String.valueOf(loginUserlist.get(0).get("SEX")); //当前用户的性别
		if("男".equals(sex)){
			sex="女";
		}else{
			sex="男";
		}
		int total=userListBiz.total_Sex(sex);	//某个性别的总数
		int pageNo; //随机数
		if(total<=20){
			pageNo=0;
		}else{
			Random ra =new Random();
			pageNo=ra.nextInt(total-20); //随机数
		}
		
		
		//如果该用户是男的    首页显示的都是女用户图像
		List<UserList> userLists=userListBiz.RanfindMember(pageNo, sex);
		for(int i=0;i<userLists.size();i++){
			userLists.get(i).setTemp1(String.valueOf(AgeUtil.getAge(userLists.get(i).getBirthday())));
		}
		if(userLists.size()<=0){
			out.print(0);
		}else{
			JSONObject jb = new JSONObject();
			jb.put("memberList", userLists);
			out.print(jb.toString());
		}
		out.flush();
		out.close();
	}

	/**
	 * 搜索
	 * @param request
	 * @param response
	 * @throws IOException 
	 */
	private void doSearch(HttpServletRequest request,HttpServletResponse response) throws IOException {
		String xianarea=request.getParameter("area").trim();
		String shen=request.getParameter("area1").trim();  //省
		String looks=request.getParameter("looks");
		int agemin=Integer.parseInt(request.getParameter("agemin"));
		int agemax=Integer.parseInt(request.getParameter("agemax"));
		
//		List<Map<String,Object>> loginUserlist=(List<Map<String, Object>>) session.getAttribute("currentUserList");
//		String sex=String.valueOf(loginUserlist.get(0).get("SEX")); //当前用户的性别
//		int total=userListBiz.total_Sex(sex);	//某个性别的总数
//		Random ra =new Random();
//		int pageNo=ra.nextInt(total-20); //随机数
		
		//如果前台直选了省份或者前台省份和区域都没有选择xianarea为null则查询所有地区的
		List<UserList> userLists = userListBiz.doSearchMember(xianarea, looks,0);
		
		List<UserList> userListss = new ArrayList<UserList>();
		if("".equals(xianarea) && !"".equals(shen)){ //前台只选择了省份没有选地区
			for(UserList u:userLists){
				if(u.getXianarea().indexOf(shen)>=0){ //如果有该省份
					userListss.add(u);
				}
			}
		}else{
			userListss=userLists;
		}
		List<UserList> userlist = new ArrayList<UserList>();
		int age;
		for(int i=0;i<userListss.size();i++){
			userListss.get(i).setTemp1(String.valueOf(AgeUtil.getAge(userListss.get(i).getBirthday())));
			age=Integer.parseInt(userListss.get(i).getTemp1());
			if( age<=agemax && age>=agemin){
				userlist.add(userListss.get(i));
			}else{
				continue;
			}
		}
		session.setAttribute(SessionAttributeNames.INDEXMEMBER, userlist);
		if(userlist.size()<=0){
			out.print(0);
		}else{
			JSONObject jb = new JSONObject();
			jb.put("memberList", userlist);
			out.print(jb.toString());
		}
		out.flush();
		out.close();
	}

	/**
	 * 重定向 随机查询数据到首页中
	 * @param request
	 * @param response
	 * @throws IOException 
	 */
	private void getNow(HttpServletRequest request, HttpServletResponse response) throws IOException {
		Object obj = session.getAttribute(SessionAttributeNames.CURRENTUSERSINFO);  
		if(obj==null){
			response.sendRedirect("login.html");
		}else{
			BhUser uf = (BhUser)obj;
			int buid=uf.getBuid(); //用户序列号
			List<Map<String,Object>> loginUserlist=userListBiz.findbByBuid(buid);
			session.setAttribute(SessionAttributeNames.CURRENTUSERLIST,loginUserlist); //存储当前用户详细信息
			
			String sex=String.valueOf(loginUserlist.get(0).get("SEX")); //当前用户的性别
			if("男".equals(sex)){
				sex="女";
			}else{
				sex="男";
			}
			int total=userListBiz.total_Sex(sex);	//某个性别的总数
			Random ra =new Random();
			System.out.println(total);
			int pageNo=ra.nextInt(total-20); //随机数
			//如果该用户是男的    首页显示的都是女用户图像
			List<UserList> userLists=userListBiz.RanfindMember(pageNo, sex);
			for(int i=0;i<userLists.size();i++){
				userLists.get(i).setTemp1(String.valueOf(AgeUtil.getAge(userLists.get(i).getBirthday())));
			}
			session.setAttribute(SessionAttributeNames.INDEXMEMBER, userLists);
			
			//成功故事
			int totalstory= storyBiz.total();
			
			int storypageNo=ra.nextInt(totalstory-7);
			List<Story> storyList=storyBiz.RandomFind(storypageNo);	//查询7个成功故事
			System.out.println(storyList);
			session.setAttribute(SessionAttributeNames.INDEXSTORY, storyList);
			
			response.sendRedirect("index.jsp");
		}
	}

	/**
	 * 注册新账户
	 */
	private void regUser(HttpServletRequest request,HttpServletResponse response) {
		//String email = request.getParameter("regemail");
		//String pwd = request.getParameter("pwd");
		String yan_word=request.getParameter("yan_word");
		
		String yanword=(String) session.getAttribute(SessionAttributeNames.CHECKCODE);
		if(yanword==null || yanword==""){//验证码过期
			out.print(1);
		}else if(!yanword.equals(yan_word)){//验证码输入错误
			out.print(2);
		}else if(yanword.equals(yan_word)){
			BhUser bu=Reflect.regInfo(request,BhUser.class);
			
			if(bhUserBiz.checkEmail(bu.getBhemail())>0){ //该邮箱已被注册
				out.print(5);
				return ;
			}
			
			if(bhUserBiz.addBhUser(bu)>0){//注册成功
				session.setAttribute(SessionAttributeNames.CURRENTUSERSINFO, bu.getBhemail());
				out.print(3);
			}else{//注册失败
				out.print(4);
			}
		}else{
			out.print(5);
		}
		out.flush();
		out.close();
	}

	/**
	 * 退出登录
	 * @param request
	 * @param response
	 */
	private void userOutLogin(HttpServletRequest request, HttpServletResponse response){
		session.setAttribute(SessionAttributeNames.CURRENTUSERSINFO, null);
		session.removeAttribute(SessionAttributeNames.CURRENTUSERSINFO);
		out.print(1);
		out.flush();
		out.close();
	}

	/**
	 * 获取当前登录用户信息
	 * @param request
	 * @param response
	 */
	private void getUserLoginInfo(HttpServletRequest request, HttpServletResponse response){
		//当前登录用户
		Object obj = session.getAttribute(SessionAttributeNames.CURRENTUSERSINFO);  
		if (obj == null){//说明没有登录
			out.print(0);
		} else{
			BhUser uf = (BhUser)obj;
			int buid=uf.getBuid(); //用户序列号
			List<Map<String,Object>> loginUserlist=userListBiz.findbByBuid(buid);
			
			JSONObject jb = new JSONObject();
			jb.put("loginUserInfo", loginUserlist);
			out.print(jb.toString());
			
		}
		out.flush();
		out.close();
	}

	/**
	 * 前台会员登录
	 * @param request
	 * @param response
	 */
	private void userLogin(HttpServletRequest request, HttpServletResponse response){

		//登陆 1、用户第一次登录  即 用户详细信息表中的昵称为null 跳转到我的资料页面    2、否则跳到index界面
		
		String email = request.getParameter("email"); //用户邮箱
		String pwd = request.getParameter("pwd"); //密码
		String buid;
		try {
			buid = bhUserBiz.findBuidFromEmail(email);
		} catch (Exception e) {
			out.println(4); //说明还没有注册的
			return;
		}
		session.setAttribute(SessionAttributeNames.CURRENTBUID, buid);
		
		String nickname=userListBiz.findNicknamefromBuid(buid); //用户昵称
				
		BhUser bu=bhUserBiz.loginBhUser(email, pwd);	//验证是否存在该用户
		if(bu!=null){	//登录成功
			session.setAttribute(SessionAttributeNames.CURRENTUSERSINFO, bu);
			if(nickname!=null){
				out.print(1);	//有昵称
			}else{
				out.print(2); 	//第一次登录	
			}
		}else{
			out.print(0);//登录失败
		}
		
		out.flush();
		out.close();
	}

	/**
	 * 发送验证码
	 * @param request
	 * @param response
	 */
	private void sendCode(HttpServletRequest request, HttpServletResponse response)
	{
		String email = request.getParameter("regemail");
		//随机生成验证码
		Random rd=new Random();
		String str="";
		while(str.length()<6){
			str+=rd.nextInt(10);
		}
		//System.out.println(str);
		
		//将验证码存入session
		session.setAttribute(SessionAttributeNames.CHECKCODE, str);
		
		//启用定时任务，2分钟后清空session重点验证码
		MyTimer myTimer=new MyTimer();
		myTimer.getTimer(session);
		
		//将验证码发送到用户邮箱
		MailUtil mailUtil=new MailUtil();
		if(mailUtil.sendMail(email,"百合网注册验证码",str)){
			//MyTimer myTimer=new MyTimer();
			//myTimer.getTimer(session);
			out.print(1);//发送成功
		}else{
			out.print(2);//发送失败
		}
	}

	/**
	 * 会员邮箱验证
	 * @param request
	 * @param response
	 */
	private void checkEmail(HttpServletRequest request, HttpServletResponse response)
	{
		//先判断该邮箱是否注册过
		String email=request.getParameter("regemail");
		if(bhUserBiz.checkEmail(email)>0){
			out.print(1);//说明改邮箱已被注册
		}else{
			out.print(2);//说明邮箱可用
		}
		out.flush();
		out.close();
	}
}
